<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ActiveAddFriendGroupMapper;
use Carbon\Carbon;
use Mine\Abstracts\AbstractService;
use Mine\MineCollection;
use Mine\MineModel;
use Mine\MineResponse;

class ActiveAddFriendGroupService extends AbstractService
{
    public function __construct(ActiveAddFriendGroupMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function groupList(array $params)
    {
        $list= $this->mapper->model::query()
            ->select(['id', 'group_name'])
            ->where('uid', $params['uid'])
            ->get();
        if($list->isNotEmpty()){
            $list=$list->toArray();
            array_unshift($list, ['id' => 0, 'group_name' => '默认分组']);
        }else{
            $list=[['id' => 0, 'group_name' => '默认分组']];
        }
        return $list;
    }

    public function saveGroup($params)
    {
        return $this->mapper->save($params);
    }

    public function groupData(array $params)
    {
        $pageSize = (int)($params['page_size']?? MineModel::PAGE_SIZE);

        $query = $this->mapper->groupData($params);
        $list = $query->paginate($pageSize);

        return $this->mapper->setPaginate($list);
    }

    public function exportGroupData(array $params, string $dto)
    {
        if (empty($dto)) {
            return container()->get(MineResponse::class)->error('导出未指定DTO');
        }

        if (empty($filename)) {
            $filename = "主动加好友-分组数据" . Carbon::now()->format('Y-m-d_H-i-s') . ".xlsx";
        }
        $query = $this->mapper->groupData($params);
        $list = $query->get();

        $list->transform(function ($item) {
            return [
                'group_name' => $item->group_name,
                'total_greetings' => $item->total_greetings,
                'passed_friends' => $item->passed_friends,
                'pass_rate' => $item->pass_rate . '%', // 转换为百分比格式
                'not_found_wechat' => $item->not_found_wechat,
            ];
        });

        // 执行导出
        return (new MineCollection())->export($dto, $filename, $list->toArray());
    }

    public function updateGroup(array $params): bool
    {
        return $this->mapper->update($params['id'],$params);
    }

}